//
//  CloseCityViewController.m
//  Logistics
//
//  Created by 华谕 on 2017/11/1.
//  Copyright © 2017年 HUYU. All rights reserved.
//

#import "CloseCityViewController.h"
#import "CityModel.h"

static NSString *cellPath = @"closeCitycell";
@interface CloseCityViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property(nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)UISearchBar *searchBar;
@property (nonatomic, strong)NSArray *priveAry;
@property (nonatomic, strong)NSArray *theCityAry;
@property (nonatomic, assign)BOOL isCity;

@end

@implementation CloseCityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
    NSDictionary *dic = @{@"level":@"1"};
    [self requestAreaList:dic];
}

- (void)creatUI
{
    self.view.backgroundColor = RGB(245, 245, 245);
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"选择省份";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:Icon(@"backimg") style:UIBarButtonItemStylePlain target:self action:@selector(dismissVc)];
    UIView *topview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45*displayheight)];
    topview.backgroundColor = RGB(204, 204, 204);
    [self.view addSubview:topview];
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(15*displaywidth, 5*displayheight, SCREEN_WIDTH-30*displaywidth, 35*displayheight)];
    _searchBar.placeholder = @"输入城市名                                                            ";
    _searchBar.backgroundColor = [UIColor clearColor];
    [_searchBar setBarTintColor:[UIColor whiteColor]];
    _searchBar.delegate = self;
    [_searchBar.layer setBorderWidth:0.5f];
    [_searchBar.layer setBorderColor:[UIColor colorWithWhite:0.7 alpha:1.0].CGColor];
    _searchBar.layer.cornerRadius = 5;
    _searchBar.layer.masksToBounds = YES;
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    [_searchBar setTintColor:[UIColor lightGrayColor]];
    [[[_searchBar.subviews objectAtIndex:0].subviews objectAtIndex:0] removeFromSuperview];
    [topview addSubview:_searchBar];
    CGFloat H = 45*displayheight;
    if (![self.cityStr isEqualToString:@""])
    {
        UIView *cityView = [[UIView alloc] initWithFrame:CGRectMake(0, 45*displayheight, SCREEN_WIDTH, 45*displayheight)];
        cityView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:cityView];
        UIImageView *imageView1 = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displayheight, 15*displaywidth, 15*displayheight) ImageName:@"sy_icon11"];
        imageView1.contentMode = UIViewContentModeScaleAspectFit;
        [cityView addSubview:imageView1];
        UILabel *cityLabel = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 5*displayheight, SCREEN_WIDTH-50*displaywidth, 35*displayheight) Font:15.0 Text:[NSString stringWithFormat:@"定位城市%@",_cityStr] Color:RGB(54, 54, 54)];
        cityLabel.textAlignment = NSTextAlignmentLeft;
        [cityView addSubview:cityLabel];
        H += 45*displayheight;

    }
    
    if ([[LTools cacheForKey:SERVER_CityArray] isKindOfClass:[NSArray class]])
    {
        NSArray *cityAry = [LTools cacheForKey:SERVER_CityArray];
        if (cityAry.count > 0)
        {
            UIView *historyView = [[UIView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, 80*displayheight)];
            historyView.backgroundColor = [UIColor whiteColor];
            [self.view addSubview:historyView];
            
            UILabel *hisCityLab = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 5*displayheight, SCREEN_WIDTH-30*displaywidth, 30*displayheight) Font:15.0 Text:@"常用城市" Color:RGB(135, 135, 135)];
            [historyView addSubview:hisCityLab];
            CGFloat W = (SCREEN_WIDTH - 70*displaywidth)/4;
            for (int i = 0; i < cityAry.count; i++)
            {
                UIButton *cityBtn = [ZCControl createButtonWithFrame:CGRectMake(20*displaywidth+(W+10*displaywidth)*i, 40*displayheight, W, 30*displayheight) ImageName:nil Target:self Action:@selector(historyAction:) Title:cityAry[i] Font:16.0];
                cityBtn.backgroundColor = RGB(232, 232, 232);
                [cityBtn setTitleColor:RGB(153, 153, 153) forState:UIControlStateNormal];
                if (i == 0)
                {
                    cityBtn.backgroundColor = RGB(255, 153, 0);
                    [cityBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                }
                cityBtn.tag = 300+i;
                [historyView addSubview:cityBtn];
                
            }
            H += 80*displayheight;
        }
        
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, H, SCREEN_WIDTH, SCREEN_HEIGHT-H-STA_NAV_HEIGHT) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    [self.view addSubview:_tableview];
    [_tableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isCity)
    {
        return _theCityAry.count;
    }
    return _priveAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_isCity)
    {
        if (_theCityAry.count > 0)
        {
            CityModel *model = _theCityAry[indexPath.row];
            cell.textLabel.text = model.name;
            cell.textLabel.font = [UIFont systemFontOfSize:15.0];
            cell.textLabel.textColor = RGB(102, 102, 102);
        }
    }
    else
    {
        if (_priveAry.count > 0)
        {
            CityModel *model = _priveAry[indexPath.row];
            cell.textLabel.text = model.name;
            cell.textLabel.font = [UIFont systemFontOfSize:15.0];
            cell.textLabel.textColor = RGB(102, 102, 102);
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isCity)
    {
        CityModel *model = _theCityAry[indexPath.row];
        NSString *idStr = [NSString stringWithFormat:@"%ld",model.ID];
        [LTools cache:model.name ForKey:SERVER_CityNew];
        [LTools cache:idStr ForKey:SERVER_CityiDNew];
        if ([[LTools cacheForKey:SERVER_CityArray] isKindOfClass:[NSArray class]])
        {
            NSArray *cityAry = [LTools cacheForKey:SERVER_CityArray];
            NSMutableArray *nowCityAry = [NSMutableArray arrayWithCapacity:0];
            [nowCityAry addObjectsFromArray:cityAry];
            NSArray *cityIdAry = [LTools cacheForKey:SERVER_CityIdArray];
            NSMutableArray *nowCityIdAry = [NSMutableArray arrayWithCapacity:0];
            [nowCityIdAry addObjectsFromArray:cityIdAry];
            if (cityAry.count == 4)
            {
                [nowCityAry removeLastObject];
                [nowCityAry insertObject:model.name atIndex:0];
                [LTools cache:nowCityAry ForKey:SERVER_CityArray];
                [nowCityIdAry removeLastObject];
                [nowCityIdAry insertObject:idStr atIndex:0];
                [LTools cache:nowCityIdAry ForKey:SERVER_CityIdArray];
            }
            else
            {
                [nowCityAry insertObject:model.name atIndex:0];
                [LTools cache:nowCityAry ForKey:SERVER_CityArray];
                [nowCityIdAry insertObject:idStr atIndex:0];
                [LTools cache:nowCityIdAry ForKey:SERVER_CityIdArray];
            }
        }
        else
        {
            NSMutableArray *nowCityAry = [NSMutableArray arrayWithCapacity:0];
            NSMutableArray *nowCityIdAry = [NSMutableArray arrayWithCapacity:0];
            [nowCityAry addObject:model.name];
            [LTools cache:nowCityAry ForKey:SERVER_CityArray];
            [nowCityIdAry addObject:idStr];
            [LTools cache:nowCityIdAry ForKey:SERVER_CityIdArray];
           
        }
        if (self.closeBlock != nil)
        {
            self.closeBlock(model.name, idStr);
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        CityModel *model = _priveAry[indexPath.row];
        NSDictionary *dic = @{@"level":@"2",
                              @"parentId":[NSString stringWithFormat:@"%ld",model.ID]
                              };
        _isCity = YES;
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回上一级" style:UIBarButtonItemStylePlain target:self action:@selector(dismissVc)];
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        [self requestAreaList:dic];
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30*displayheight)];
    myView.backgroundColor = RGB(204, 204, 204);
    UILabel *titLabel = [ZCControl createLabelWithFrame:CGRectMake(15*displaywidth, 0, SCREEN_WIDTH-30*displaywidth, 30*displayheight) Font:15.0 Text:@"选择城市" Color:RGB(53, 53, 53)];
    [myView addSubview:titLabel];
    return myView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45*displayheight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30*displayheight;
}
//常用城市
- (void)historyAction:(UIButton *)btn
{
    NSInteger index = btn.tag-300;
    NSArray *cityAry = [LTools cacheForKey:SERVER_CityArray];
    NSArray *cityIdAry = [LTools cacheForKey:SERVER_CityIdArray];
    
    [LTools cache:cityAry[index] ForKey:SERVER_CityNew];
    [LTools cache:cityIdAry[index] ForKey:SERVER_CityiDNew];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    NSString *searchKey = searchBar.text;
    if ([searchKey isEqualToString:@""] == YES) {
        
        [LTools showMBProgressWithText:@"请输入搜索城市名" addToView:self.view];
        return;
    }
    _isCity = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回上一级" style:UIBarButtonItemStylePlain target:self action:@selector(dismissVc)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    NSDictionary *dic = @{@"name":searchKey,
                          @"level":@"2"
                          };
    [self requestAreaList:dic];
}

- (void)dismissVc
{
    if (_isCity)
    {
        _isCity = NO;
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:Icon(@"backimg") style:UIBarButtonItemStylePlain target:self action:@selector(dismissVc)];
        [self.tableview reloadData];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
}

- (void)requestAreaList:(NSDictionary *)dic
{
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestAreaListParmers:dic Success:^(id obj) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
        if ([obj server_Getcodecheck])
        {
            if (_isCity)
            {
                _theCityAry = [CityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            }
            else
            {
                _priveAry = [CityModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            }
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableview reloadData];
        });
    } failed:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
